package com.kgc.sbt.provider;

import com.alibaba.dubbo.config.annotation.Service;
import com.kgc.sbt.api.CouponReceiveApi;
import com.kgc.sbt.domain.CouponReceive;
import com.kgc.sbt.domain.CouponReceiveExample;
import com.kgc.sbt.mapper.CouponReceiveMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @author Shan
 * @date 2021/6/22
 * @return
 * @description
 */

@Service
@Slf4j
public class CouponReceiveProvider implements CouponReceiveApi {

    @Autowired
    private CouponReceiveMapper couponReceiveMapper;

    @Override
    public boolean insertCouponReceive(CouponReceive couponReceive) {
        return couponReceiveMapper.insert(couponReceive)==1?true:false;
    }

   /**
    * @author Shan
    * @date 2021/6/23
    * @return
    * @description 查询用户是否存在未使用的指定优惠券
    */
    @Override
    public boolean queryCouponByUserIdAndCouponId(Integer userId, Integer couponId) {
        CouponReceiveExample couponReceiveExample=new CouponReceiveExample();
        CouponReceiveExample.Criteria criteria=couponReceiveExample.createCriteria();
        criteria.andUserIdEqualTo(userId);
        criteria.andCouponIdEqualTo(couponId);
        criteria.andStatusEqualTo(0);

        couponReceiveExample.or(criteria);
        return couponReceiveMapper.selectByExample(couponReceiveExample).size()==0?false:true;
    }





    @Override
    public boolean modCouponReceive(Integer userId, Integer couponId) {

        CouponReceiveExample couponReceiveExample=new CouponReceiveExample();
        CouponReceiveExample.Criteria criteria=couponReceiveExample.createCriteria();
        criteria.andUserIdEqualTo(userId);
        criteria.andCouponIdEqualTo(couponId);
        couponReceiveExample.or(criteria);
        List<CouponReceive> couponReceives=couponReceiveMapper.selectByExample(couponReceiveExample);
        log.error("查询到的优惠券：{}",couponReceives);
        if (couponReceives.isEmpty()){
            return false;
        }
        log.error("查到数据了！");
        //设置为已使用
        CouponReceive couponReceive=couponReceives.get(0);
        couponReceive.setStatus(1);
        couponReceiveMapper.updateByPrimaryKey(couponReceive);

        return true;
    }
}
